package fr.sedoo.rbv.geonetwork.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Iterator;
import java.util.List;

import javax.sql.DataSource;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.simple.ParameterizedRowMapper;

/**
 * Le service XML listant les groupes fournit uniquement la liste des groupe ajoutés et non les groupes crées de base par Geonetwork: All, Guest, ...
 * L'objectif de cette implémentation est l'obtention de ces informations via une requête directe. 
 * @author andre
 *
 */
public class JDBCGroupDAO implements GroupDAO 
{
	private DataSource dataSource;
	List<GeonetworkGroup> groups = null;
	
	@Override
	public List<GeonetworkGroup> getGroups() 
	{
		if (groups == null)
		{
			String sql = "SELECT * FROM groups";
			JdbcTemplate template = new JdbcTemplate(getDataSource());
			groups = template.query(sql, new GeonetworkGroupRowMapper());
		}
		return groups;
	}
	
	public DataSource getDataSource() {
		return dataSource;
	}

	public void setDataSource(DataSource dataSource) {
		this.dataSource = dataSource;
	}

	class GeonetworkGroupRowMapper implements ParameterizedRowMapper<GeonetworkGroup>
	{

		@Override
		public GeonetworkGroup mapRow(ResultSet rs, int rowNum) throws SQLException {
			GeonetworkGroup group = new GeonetworkGroup();
			group.setId(rs.getLong("id"));
			group.setName(rs.getString("name"));
			return group;
		}
		
	}

	@Override
	public GeonetworkGroup getGroupByName(String name) {
		//On force l'appel à getGroups
		List<GeonetworkGroup> localGroup = getGroups();
		Iterator<GeonetworkGroup> iterator = localGroup.iterator();
		while (iterator.hasNext()) 
		{
			GeonetworkGroup current = iterator.next();
			if (current.getName().compareToIgnoreCase(name)==0)
			{
				return current;
			}
		}
		return null;
	}
	

}
